import csv from "csv-parser";
import iconv from "iconv-lite";
import fs from "fs";

function csvDetail(filename, type) {
    const results:any = [];
    return new Promise((resolve, reject) => {
        const stream = type === "alipay" ? fs.createReadStream(filename).pipe(iconv.decodeStream("GB2312")) : fs.createReadStream(filename, { encoding: "utf-8" });
        stream
            .on("data", (data) => {
                const detailData = data.split("\n");
                const linesToSkip = type === "alipay" ? 24 : type === "wechat" ? 16 : 0;
                const headers = detailData[linesToSkip].trim().split(","); // 获取标题行
                for (let i = linesToSkip + 1; i < detailData.length; i++) {
                    const line = detailData[i].trim();
                    if (line) {
                        // 确保不处理空行
                        const values = line.split(",");
                        let record = {};
                        headers.forEach((header, index) => {
                            record[header] = values[index];
                        });
                        results.push(record);
                    }
                }
            })
            .on("end", () => resolve(results))
            .on("error", (err) => reject(err));

        //// 处理csv文件没有注释的情况
        // fs.createReadStream(filename)
        //     .pipe(iconv.decodeStream("GB2312")) // 转换为 UTF-8
        //     .pipe(
        //         csv({
        //             mapHeaders: ({ header }) => header.trim(), // 去除头部的多余空格
        //         })
        //     )
        //     .on("data", (data) => {
        //         results.push(data);
        //         console.log(results);
        //     })
        //     .on("end", () => resolve(results))
        //     .on("error", (err) => reject(err));
    });
}

export default csvDetail;
// 提供csv文件路径返回读取的数据，这里的cvs支付宝是gb2312编码，微信是utf-8编码的
